<% layout('/layouts/default.html', {title: '车辆详情管理', libs: ['validate','fileupload']}){ %>
<div class="main-content">
	<div class="box box-main">
		<div class="box-header with-border">
			<div class="box-title">
				<i class="fa icon-note"></i> ${text(car.isNewRecord ? '新增车辆' : '编辑车辆')}
			</div>
			<div class="box-tools pull-right hide">
				<button type="button" class="btn btn-box-tool" data-widget="collapse"><i class="fa fa-minus"></i></button>
			</div>
		</div>
		<#form:form id="inputForm" model="${car}" action="${ctx}/car/car/saveCar" method="post" class="form-horizontal">
			<div class="box-body">
				<div class="form-unit">${text('基本信息')}</div>
				<#form:hidden path="carId"/>
				<#form:hidden path="carStatus" defaultValue="0"/>
				<div class="row">
					<div class="col-xs-4">
						<div class="form-group">
							<label class="control-label col-sm-4" title="">
								<span class="required ">*</span> ${text('车辆类型')}：<i class="fa icon-question hide"></i></label>
							<div class="col-sm-8">
								<#form:treeselect id="typeId" title="${text('车型选择')}" placeholder="请选择车辆类型"
									path="typeId" labelPath="treeName"
									url="${ctx}/car/carType/treeData?typeCode=${car.typeId}"
									callbackFuncName="typeSelectCallback"
									class="" allowClear="true" canSelectRoot="true" canSelectParent="true"/>
							</div>
						</div>
					</div>
					<div class="col-xs-4">
						<div class="form-group">
							<label class="control-label col-sm-4" title="">
								<span class="required ">*</span> ${text('车辆名称')}：<i class="fa icon-question hide"></i></label>
							<div class="col-sm-8">
								<#form:input path="carTitle" maxlength="64" placeholder="请输入车辆名称" class="form-control required"/>
							</div>
						</div>
					</div>
					<div class="col-xs-4">
						<div class="form-group">
							<label class="control-label col-sm-4" title="">
								<span class="required ">*</span> ${text('车辆归属地')}：<i class="fa icon-question hide"></i></label>
							<div class="col-sm-8">
								<#form:input path="originPlace" maxlength="64" class="form-control required"/>
							</div>
						</div>
					</div>
					<div class="col-xs-4">
						<div class="form-group">
							<label class="control-label col-sm-4" title="">
								<span class="required ">*</span> ${text('看车地点')}：<i class="fa icon-question hide"></i></label>
							<div class="col-sm-8">
								<#form:input path="lookCarPlace" maxlength="64" class="form-control required"/>
							</div>
						</div>
					</div>
					<div class="col-xs-4 hide" id="brand">
						<div class="form-group">
							<label class="control-label col-sm-4" title="">
								<span class="required">*</span> ${text('车辆品牌')}：<i class="fa icon-question hide"></i></label>
							<div class="col-sm-8">
								<#form:select path="brandId" items="${brandList}" itemLabel="title" itemValue="brandId" class="form-control required" />
							</div>
						</div>
					</div>
					<div class="col-xs-4">
						<div class="form-group">
							<label class="control-label col-sm-4" title="">
								<span class="required">*</span> ${text('车型')}：<i class="fa icon-question hide"></i></label>
							<div class="col-sm-8">
								<#form:input path="carModel" maxlength="64" class="form-control required"/>
							</div>
						</div>
					</div>
					<div class="col-xs-4">
						<div class="form-group">
							<label class="control-label col-sm-4" title="">
								<span class="required">*</span> ${text('车身颜色')}：<i class="fa icon-question hide"></i></label>
							<div class="col-sm-8">
								<#form:input path="carColor" maxlength="64" class="form-control required"/>
							</div>
						</div>
					</div>
					<div class="col-xs-4">
						<div class="form-group">
							<label class="control-label col-sm-4" title="">
								<span class="required ">*</span> ${text('原价')}：<i class="fa icon-question hide"></i></label>
							<div class="col-sm-8">
								<#form:input path="originalPrice" placeholder="以元为单位" maxlength="10" class="form-control required digits"/>
							</div>
						</div>
					</div>
					<div class="col-xs-4">
						<div class="form-group">
							<label class="control-label col-sm-4" title="">
								<span class="required ">*</span> ${text('售价')}：<i class="fa icon-question hide"></i></label>
							<div class="col-sm-8">
								<#form:input path="sellPrice" placeholder="以元为单位" maxlength="10" class="form-control required digits"/>
							</div>
						</div>
					</div>
					<div class="col-xs-4">
						<div class="form-group">
							<label class="control-label col-sm-4" title="">
								<span class="required">*</span> ${text('公里数')}：<i class="fa icon-question hide"></i></label>
							<div class="col-sm-8">
								<#form:input path="kilometer" maxlength="32" class="form-control required"/>
							</div>
						</div>
					</div>
					<div class="col-xs-4">
						<div class="form-group">
							<label class="control-label col-sm-4" title="">
								<span class="required">*</span> ${text('标签')}：<i class="fa icon-question hide"></i></label>
							<div class="col-sm-8">
								<#form:select path="carLabel" dictType="h_car_label" class="form-control required" />
							</div>
						</div>
					</div>
					<div class="col-xs-4">
						<div class="form-group">
							<label class="control-label col-sm-4" title="">
								<span class="required hide">*</span> ${text('汽缸')}：<i class="fa icon-question hide"></i></label>
							<div class="col-sm-8">
								<#form:input path="cylinder" maxlength="16" class="form-control"/>
							</div>
						</div>
					</div>
					<div class="col-xs-4">
						<div class="form-group">
							<label class="control-label col-sm-4" title="">
								<span class="required">*</span> ${text('过户次数')}：<i class="fa icon-question hide"></i></label>
							<div class="col-sm-8">
								<#form:input path="transfers" maxlength="3" class="form-control digits required"/>
							</div>
						</div>
					</div>
					<div class="col-xs-4">
						<div class="form-group">
							<label class="control-label col-sm-4" title="">
								<span class="required">*</span> ${text('上户日期')}：<i class="fa icon-question hide"></i></label>
							<div class="col-sm-8">
								<#form:input path="registerDate" readonly="true" maxlength="20" class="form-control laydate required"
								dataFormat="date" data-type="date" data-format="yyyy-MM"/>
							</div>
						</div>
					</div>
					<div class="col-xs-4">
						<div class="form-group">
							<label class="control-label col-sm-4" title="">
								<span class="required hide">*</span> ${text('详情电话')}：<i class="fa icon-question hide"></i></label>
							<div class="col-sm-8">
								<#form:input path="detailTel" maxlength="32" class="form-control"/>
							</div>
						</div>
					</div>
				</div>
				<div class="row">
					<div class="col-xs-12">
						<div class="form-group">
							<label class="control-label col-sm-2 col-sm-9-1" title="">
								<span class="required hide">*</span> ${text('具体车况')}：<i class="fa icon-question hide"></i></label>
							<div class="col-sm-10 col-sm-9-8">
								<#form:textarea path="explain" placeholder="请填写改装、保险、事故等相关情况" rows="4" maxlength="500" class="form-control"/>
							</div>
						</div>
					</div>
				</div>
				<div class="row">
					<div class="col-xs-12">
						<div class="form-group">
							<label class="control-label col-sm-2 col-sm-9-1" title="">
								<span class="required hide">*</span> ${text('备注信息')}：<i class="fa icon-question hide"></i></label>
							<div class="col-sm-10 col-sm-9-8">
								<#form:textarea path="remarks" rows="4" maxlength="500" class="form-control"/>
							</div>
						</div>
					</div>
				</div>
				<div class="form-unit">${text('图片信息')}</div>
				<div class="row">
					<div class="col-xs-12">
						<div class="form-group">
							<label class="control-label col-sm-2 col-sm-9-1">
								<span class="required">*</span> ${text('封面照片')}：</label>
							<div class="col-sm-10 col-sm-9-8">
								<div class="custom-box">
									<div class="custom-center-title">
										<ul class="custom-ul" id="image"></ul>
										<div id="showBtn" class="custom-center">
											<i class="fa fa-image custom-icon"></i>
											<div class="custom-file">
												<span>点击选择图片</span>
												<input type="file" accept="image/*" class="cover-file" id="cover">
											</div>
											<span class="custom-tips">最多可选择 1 张图片呦~</span>
										</div>
									</div>
								</div>
							</div>
						</div>
					</div>
				</div>
				<div class="row">
					<div class="col-xs-12">
						<div class="form-group">
							<label class="control-label col-sm-2 col-sm-9-1">
								<span class="required">*</span> ${text('轮播图片')}：</label>
							<div class="col-sm-10 col-sm-9-8">
								<div class="custom-box">
									<div id="topTitle1" class="custom-title carousel hide">
										<div class="custom-count">最多可选择 4 张图片呦~</div>
										<div class="custom-add" id="topAdd1">
											<span>继续添加</span>
											<input type="file" accept="image/*" multiple class="cover-file" data-type="1">
										</div>
									</div>
									<div class="custom-center-title">
										<ul class="custom-ul" id="image1"></ul>
										<div id="showBtn1" class="custom-center">
											<i class="fa fa-image custom-icon"></i>
											<div class="custom-file">
												<span>点击选择图片</span>
												<input type="file" accept="image/*" multiple class="cover-file carousel">
											</div>
											<span class="custom-tips">最多可选择 4 张图片呦~</span>
										</div>
									</div>
								</div>
							</div>
						</div>
					</div>
				</div>
				<div class="row">
					<div class="col-xs-12">
						<div class="form-group">
							<label class="control-label col-sm-2 col-sm-9-1">
								<span class="required">*</span> ${text('详情图片')}：</label>
							<div class="col-sm-10 col-sm-9-8">
								<div class="custom-box">
									<div id="topTitle2" class="custom-title detail hide">
										<div class="custom-count">最多可选择 9 张图片呦~</div>
										<div class="custom-add" id="topAdd2">
											<span>继续添加</span>
											<input type="file" accept="image/*" multiple class="cover-file" data-type="1">
										</div>
									</div>
									<div class="custom-center-title">
										<ul class="custom-ul" id="image2"></ul>
										<div id="showBtn2" class="custom-center">
											<i class="fa fa-image custom-icon"></i>
											<div class="custom-file">
												<span>点击选择图片</span>
												<input type="file" accept="image/*" multiple class="cover-file detail">
											</div>
											<span class="custom-tips">最多可选择 9 张图片呦~</span>
										</div>
									</div>
								</div>
							</div>
						</div>
					</div>
				</div>
			</div>
			<div class="box-footer">
				<div class="row">
					<div class="col-sm-offset-2 col-sm-10">
						<% if (hasPermi('car:car:edit')){ %>
							<button type="submit" class="btn btn-sm btn-primary" id="btnSubmit"><i class="fa fa-check"></i> ${text('保 存')}</button>&nbsp;
						<% } %>
						<button type="button" class="btn btn-sm btn-default" id="btnCancel" onclick="js.closeCurrentTabPage()"><i class="fa fa-reply-all"></i> ${text('关 闭')}</button>
					</div>
				</div>
			</div>
		</#form:form>
	</div>
</div>
<% } %>
<script>

	let imgList = [],imgList1 = [],imgList2 = [],deleteInfo={cover:[],carousel:[],detail:[]};
	// 上传图片
	$('#cover').on('change',function (e) {
		let img = e.target.files;
		const fix = (new Date()).getTime();
		for(let i=0;i<img.length;i++) {
			img[i].imgType='new';
			const name = (img[i].name).split('.');
			const file = new File([img[i]], 'cover_' + (fix+i) + '.' + name[1]);
			imgList=imgList.concat(file);
		}
		imgShow(0,imgList);
	});
	$('.carousel').on('change',function (e) {
		let img = e.target.files;
		const fix = (new Date()).getTime();
		for(let i=0;i<img.length;i++) {
			if(imgList1.length>8){
				break;
			}
			img[i].imgType='new';
			const name = (img[i].name).split('.');
			const file = new File([img[i]], 'carousel_' + (fix+i) + '.' + name[1]);
			imgList1=imgList1.concat(file);
		}
		imgShow(1,imgList1);
	});
	$('.detail').on('change',function (e) {
		let img = e.target.files;
		const fix = (new Date()).getTime();
		for(let i=0;i<img.length;i++) {
			if(imgList2.length>8){
				break;
			}
			img[i].imgType='new';
			const name = (img[i].name).split('.');
			const file = new File([img[i]], 'detail_' + (fix+i) + '.' + name[1]);
			imgList2=imgList2.concat(file);
		}
		imgShow(2,imgList2);
	});
	// 显示图片列表
	function imgShow(index,attr){
		let html = '';
		let windowURL = window.URL || window.webkitURL;
		for(let i =0;i<attr.length;i++) {
			let dataURL = windowURL.createObjectURL(attr[i]);
			html +='<li class="custom-li">' +
					'<div class="custom-trash" onclick="removeImg('+ index +','+i+')"><i class="fa fa-trash custom-del"></i></div>' +
					'<div><img class="custom-img" src="'+dataURL+'"></div>' +
					'<div class="custom-load">等待上传</div>' +
					'</li>';
			windowURL.revokeObjectURL(attr[i]);
		}
		if(index==0){
			if(attr.length>0){
				$('#showBtn').hide();
			}else{
				$('#showBtn').show();
			}
			$('#image').html(html);
		}
		if(index==1){
			if(attr.length>0){
				$('#showBtn1').hide();
				$('#topTitle1').removeClass("hide");
			}
			if(attr.length>3){
				$('#topAdd1').hide();
			}
			$('#image1').html(html);
		}
		if(index==2){
			if(attr.length>0){
				$('#showBtn2').hide();
				$('#topTitle2').removeClass("hide");
			}
			if(attr.length>8){
				$('#topAdd2').hide();
			}
			$('#image2').html(html);
		}
	}
	// 移除图片
	function removeImg(index,obj){
		js.confirm('确认删除该图片吗？', function(){
			if(index==0){
				$.each(imgList,(index)=>{
					if(index==obj){
						if(!imgList[obj].imgType){
							const img = imgList[obj].split("/");
							deleteInfo.cover.push(img[img.length-1])
						}
						imgList.splice(index,1);
					}
				});
				imgShow(0,imgList);
			}
			if(index==1){
				$.each(imgList1,(index)=>{
					if(index==obj){
						if(!imgList1[obj].imgType){
							const img = imgList1[obj].split("/");
							deleteInfo.carousel.push(img[img.length-1])
						}
						imgList1.splice(index,1);
					}
				});
				imgShow(1,imgList1);
			}
			if(index==2){
				$.each(imgList2,(index)=>{
					if(index==obj){
						if(!imgList2[obj].imgType){
							const img = imgList2[obj].split("/");
							deleteInfo.detail.push(img[img.length-1])
						}
						imgList2.splice(index,1);
					}
				});
				imgShow(2,imgList2);
			}
		});
	}
	// 保存
	$("#inputForm").validate({
		submitHandler: function(form){
			let formData = $(form).serializeArray();
			saveFileData(formData);
		}
	});
	function saveFileData(formData) {
		if(imgList.length==0){
			js.showMessage('封面图片未上传！！');
			return;
		}
		if(imgList1.length==0){
			js.showMessage('轮播图片未上传！！');
			return;
		}
		if(imgList2.length==0){
			js.showMessage('详情图片未上传！！');
			return;
		}
		let paramsImg = new FormData();
		$.each(formData, function(i, obj) {
			paramsImg.append(obj.name,obj.value);
		});
		for(let i=0;i<imgList.length;i++){
			paramsImg.append('files',imgList[i]);
		}
		for(let i=0;i<imgList1.length;i++){
			paramsImg.append('files',imgList1[i]);
		}
		for(let i=0;i<imgList2.length;i++){
			paramsImg.append('files',imgList2[i]);
		}
		js.confirm('确认提交吗？', function(){
			$.ajax({
				url : '${ctx}/car/car/saveCar',
				type : 'POST',
				data : paramsImg,
				dataType : 'JSON',
				contentType:false,
				processData:false,
				mimeType:"multipart/form-data",
				success : function(data) {
					js.showMessage(data.message);
					if(data.result == 'true'){
						js.closeCurrentTabPage(function(contentWindow){
							contentWindow.page();
						});
					}
				}
			});
		});
	}
	// 自定义回调函数：类型选择后触发
	function typeSelectCallback(id, act, index, layero, nodes) {
		// 只处理“选择确定”和“清空选择”动作
		if (id === 'typeId') { // 确保是类型选择器的回调
			if (act === 'ok') {
				// 1. 从nodes中获取选中的类型ID（单选时nodes[0]是选中节点）
				var typeId = nodes[0].id; // 假设节点的id字段对应类型ID
				console.log("选中的类型ID：", typeId);

				// 2. 调用品牌查询接口（复用之前的品牌查询逻辑）
				queryBrandsByTypeId(typeId);
			} else if (act === 'clear') {
				// 3. 若清空类型选择，同步清空品牌下拉框
				$("#brandId").empty().append('<option value="">请先选择车辆类型</option>');
			}
		}
	}

	// 封装品牌查询逻辑（复用）
	function queryBrandsByTypeId(typeId) {

		if (!typeId) return;
		// 显示加载提示（用layer的load方法，返回加载索引）
		var loadIndex = layer.load(2, {
			shade: [0.3, '#fff'], // 遮罩层样式
			time: 10000 // 10秒后自动关闭（防止接口超时无反应）
		});
		$.ajax({
			url: "${ctx}/brand/brand/findList", // 后端查询品牌的接口
			type: "get",
			data: { typeCode: typeId },
			dataType: "json",
			success: function(data) {
				layer.close(loadIndex); // 关闭加载提示
				var brandSelect = $("#brandId");
				$("#brand").removeClass('hide')
				brandSelect.empty();
				if ( data.length > 0) {
					brandSelect.append('<option value="">请选择品牌</option>');
					$.each(data, function(i, brand) {
						brandSelect.append('<option value="' + brand.brandId + '">' + brand.title + '</option>');
					});
				} else {
					brandSelect.append('<option value="">该类型暂无品牌</option>');
					layer.msg("未查询到品牌数据", { icon: 5 }); // 提示信息
				}
			},
			error: function() {
				layer.close(loadIndex); // 关闭加载提示
				layer.msg("品牌查询失败，请重试", { icon: 2 }); // 错误提示
			}
		});

	}
</script>